<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :rules="rules2" size="small" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="中标金额(万元)" >

      </el-form-item>
      <el-form-item style="width:80px;margin-left: 0px;" prop="startAmount">
        <el-input
          v-model="queryParams.startAmount"
          clearable
        />
      </el-form-item>
      <el-form-item  style="width:15px;margin-right: 0px;">
        --
      </el-form-item>
      <el-form-item style="width:80px"  prop="endAmount">
        <el-input
          v-model="queryParams.endAmount"
          clearable
        />
      </el-form-item>
      <el-form-item label="工程名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入工程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建设单位" prop="constructEnterprise">
        <el-input
          v-model="queryParams.constructEnterprise"
          placeholder="请输入建设单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="中标时间">
        <el-date-picker
          v-model="daterangeBidedTime"
          style="width: 210px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="完工状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择完工状态" clearable>
          <el-option
            v-for="dict in dict.type.current_project_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 以下为高级查询 -->
      <!--<el-form-item label="预计竣工日期" v-show="showHighSearch">
        <el-date-picker
          v-model="daterangeEstimatedCompleteTime"
          style="width: 210px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>-->
      <el-form-item label="(预)竣工日期" prop="completedTime" v-show="showHighSearch">
        <el-date-picker
          v-model="daterangeCompletedTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="项目经理" prop="projectManager" v-show="showHighSearch">
        <el-input
          v-model="queryParams.projectManager"
          placeholder="请输入项目经理"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键点" prop="keyPoints" v-show="showHighSearch">
        <el-input
          v-model="queryParams.keyPoints"
          placeholder="请输入关键点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="success" icon="el-icon-search" size="mini" @click='showHighSearch=!showHighSearch'>高级搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:current_project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:current_project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:current_project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:current_project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="current_projectList" @selection-change="handleSelectionChange"  @sort-change="sortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工程名称" align="left" header-align="center" prop="projectName" width="350" fixed/>
      <el-table-column label="建设单位" align="center" prop="constructEnterprise" width="210" fixed/>
      <el-table-column label="中标时间" align="center" prop="bidedTime" width="180" sortable="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bidedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="预计竣工日期" align="center" prop="estimatedCompleteTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estimatedCompleteTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="(预)竣工日期" align="center" prop="completedTime" width="130" sortable="true"/>
      <el-table-column label="中标金额(万元)" align="center" prop="bidAmount" width="110"/>
      <!-- <el-table-column label="预计投标时间" align="center" prop="estimatedBidTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estimatedBidTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="装饰或幕墙面积(平方米)" align="center" prop="wallArea" width="210"/>
      <el-table-column label="项目经理" align="center" prop="projectManager" width="100" />
      <el-table-column label="关键点" align="center" prop="keyPoints" />
      <el-table-column label="获奖数量" align="center" >
      <template slot-scope="scope">
        <router-link :to="'/business/current_project_award-index/index/' + scope.row.projectId" class="link-type">
          <span>{{ scope.row.awardNumber }}</span>
        </router-link>
      </template>
    </el-table-column>
      <el-table-column label="项目文件" align="center" >
        <template slot-scope="scope">
          <router-link :to="'/business/info-index/index/' + scope.row.projectId" class="link-type">
            <span>{{ scope.row.infoNumber }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:current_project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:current_project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目基本资料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-row>
          <el-col :span="12">
        <el-form-item label="工程名称" prop="projectName" style="width:400px;">
          <el-input v-model="form.projectName" placeholder="请输入工程名称" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="建设单位" prop="constructEnterprise" style="width:400px;">
          <el-input v-model="form.constructEnterprise" placeholder="请输入建设单位" />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="中标时间" prop="bidedTime">
          <el-date-picker clearable
            v-model="form.bidedTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择中标时间">
          </el-date-picker>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <!--<el-form-item label="预计竣工日期" prop="estimatedCompleteTime">
          <el-date-picker clearable
            v-model="form.estimatedCompleteTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预计竣工日期">
          </el-date-picker>
        </el-form-item>-->
            <el-form-item label="(预)竣工日期" prop="completedTime">
              <el-date-picker clearable
                              v-model="form.completedTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择竣工日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="中标金额(万元)" prop="bidAmount" style="width:400px;">
              <el-input v-model="form.bidAmount" placeholder="请输入中标金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装饰或幕墙面积(平方米)" prop="wallArea" style="width:400px;">
              <el-input v-model="form.wallArea" placeholder="请输入装饰或幕墙面积" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        <!--  <el-col :span="12">
         <el-form-item label="预计投标时间" prop="estimatedBidTime">
          <el-date-picker clearable
            v-model="form.estimatedBidTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预计投标时间">
          </el-date-picker>
        </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="项目经理" prop="projectManager" style="width:400px;">
              <el-select
                v-model="form.projectManager"
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入项目经理">
                <el-option
                  v-for="item in options"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-row>

          <el-col :span="24">
          <el-form-item label="关键点" prop="keyPoints" style="width:880px;">
            <el-input type="textarea" maxlength="500" show-word-limit v-model="form.keyPoints"></el-input>
          </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">项目与人员关联信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCurrentProjectPresonMap">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteCurrentProjectPresonMap">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="currentProjectPresonMapList" :row-class-name="rowCurrentProjectPresonMapIndex" @selection-change="handleCurrentProjectPresonMapSelectionChange" ref="currentProjectPresonMap">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column align="center" prop="index" width="50"/>

          <!-- el-table-column label="人员类别" prop="personType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.personType" placeholder="请选择人员类别" @change="((val)=>getPersonByType(val,scope.row))">
                <el-option
                  v-for="dict in dict.type.pm_person_type"
                  :key="dict.value"
                  :value="dict.value"
                  :label="dict.label">
                </el-option>
              </el-select>
            </template>
          </el-table-column> -->
          <el-table-column label="人员" prop="personName">
            <template slot-scope="scope">
              <!-- el-select v-model="scope.row.personId" placeholder="请选择人员" clearable  @focus="updateforce">

                <el-option
                  v-for="personOption in scope.row.projectPersonList"
                  :key="personOption.personId"
                  :label="personOption.personName"
                  :value="personOption.personId">
                </el-option>
              </el-select -->
              <el-cascader
                v-model="scope.row.selectedPerson"
                :options="personOptions"
                :props="{ expandTrigger: 'hover' }">
              </el-cascader>
            </template>
          </el-table-column>
          <el-table-column label="人员是否锁定" prop="personName">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.locked"
                active-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCurrent_project, getCurrent_project, delCurrent_project, addCurrent_project, updateCurrent_project } from "@/api/business/current_project";
import { select_pms,get_person_by_type } from "@/api/business/project_person";

export default {
  name: "Current_project",
  dicts: ['pm_major', 'pm_person_title', 'pm_person_external', 'pm_person_work_status', 'pm_person_type','current_project_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCurrentProjectPresonMap: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //高级搜索
      showHighSearch: false,
      // 总条数
      total: 0,
      // 项目基本资料表格数据
      current_projectList: [],
      // 现存项目与人员关联表格数据
      currentProjectPresonMapList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 临时人员姓名时间范围
      daterangeBidedTime: [],
      // 临时人员姓名时间范围
      daterangeEstimatedCompleteTime: [],
      daterangeCompletedTime: [],
      // 临时人员姓名时间范围
      daterangeEstimatedBidTime: [],
      //项目经理
      options: [],
      personOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        constructEnterprise: null,
        bidedTime: null,
        estimatedCompleteTime: null,
        completedTime: null,
        bidAmount: null,
        estimatedBidTime: null,
        wallArea: null,
        projectManager: null,
        keyPoints: null,
        startAmount: null,
        endAmount: null,
        status: null,
      },
      // 表单参数
      form: {},
      rules2: {

        startAmount: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              } else {
                if (!this.isNumber(value)) {
                  callback(new Error('请输入数字值'))
                } else {
                  if(this.isNumber(this.queryParams.endAmount)&& this.queryParams.endAmount<value){
                    callback(new Error('最小值不能大于最大值'))
                  }else{
                    callback()
                  }
                }
              }
            }, trigger: "blur" }
        ],
        endAmount: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              } else {
                if (!this.isNumber(value)) {
                  callback(new Error('请输入数字值'))
                }else {
                if(this.isNumber(this.queryParams.endAmount)&& this.queryParams.startAmount>value){
                  callback(new Error('最小值不能大于最大值'))
                }else{
                  callback()
                }
                }
              }
            }, trigger: "blur" }
        ]
      },
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "工程名称不能为空", trigger: "blur" }
        ],
        constructEnterprise: [
          { required: true, message: "建设单位不能为空", trigger: "blur" }
        ],
     /*   bidedTime: [
          { required: true, message: "中标时间不能为空", trigger: "blur" }
        ],*/
        bidAmount: [
          { required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('中标金额不能为空'))
              } else {
                if (!this.isNumber(value)) {
                  callback(new Error('请输入数字值'))
                } else {
                  callback()
                }
              }
            }, trigger: "blur" }
        ],
        estimatedBidTime: [
          { required: true, message: "预计投标时间不能为空", trigger: "blur" }
        ],
        keyPoints: [
          { required: true, message: "关键点不能为空", trigger: "blur" }
        ],
        wallArea: [
          {  required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('装饰或幕墙面积不能为空'))
              } else {
                if (!this.isNumber(value)) {
                  callback(new Error('请输入数字值'))
                } else {
                  callback()
                }
              }
            }, trigger: "blur" }
        ],
        projectManager: [
          { required: true, message: "项目经理不能为空", trigger: "blur" }
        ],
        bidAmount: [
          { required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('金额不能为空'))
              } else {
                if (!this.isNumber(value)) {
                  callback(new Error('请输入数字值'))
                } else {
                  callback()
                }
              }
            }, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //排序
    sortChange(column, prop, order) {
      // ascending 升序
      this.sort =
        column.order == "ascending"
          ? "asc" : "desc";
      this.sortField =column.prop;
      this.getList();
    },

    /** 查询项目基本资料列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeBidedTime && '' != this.daterangeBidedTime) {
        this.queryParams.params["beginBidedTime"] = this.daterangeBidedTime[0];
        this.queryParams.params["endBidedTime"] = this.daterangeBidedTime[1];
      }
      if (null != this.daterangeEstimatedCompleteTime && '' != this.daterangeEstimatedCompleteTime) {
        this.queryParams.params["beginEstimatedCompleteTime"] = this.daterangeEstimatedCompleteTime[0];
        this.queryParams.params["endEstimatedCompleteTime"] = this.daterangeEstimatedCompleteTime[1];
      }
      if (null != this.daterangeCompletedTime && '' != this.daterangeCompletedTime) {
        this.queryParams.params["beginCompletedTime"] = this.daterangeCompletedTime[0];
        this.queryParams.params["endCompletedTime"] = this.daterangeCompletedTime[1];
      }
      if (null != this.daterangeEstimatedBidTime && '' != this.daterangeEstimatedBidTime) {
        this.queryParams.params["beginEstimatedBidTime"] = this.daterangeEstimatedBidTime[0];
        this.queryParams.params["endEstimatedBidTime"] = this.daterangeEstimatedBidTime[1];
      }
      if (null != this.sortField && '' != this.sortField && null != this.sort && '' != this.sort) {
        this.queryParams.params["sortField"] = this.sortField;
        this.queryParams.params["sort"] = this.sort;
      }
      listCurrent_project(this.queryParams).then(response => {
        this.current_projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleMinChange(value) {
      this.verification()
    },
    handleMaxChange(value) {
      this.verification()
    },
    //字段验证
    verification(){
      if(this.queryParams.startAmount>this.queryParams.endAmount){
        this.$message.warning("起始数不能大于结束数");
        return false;
      }else{
        return true;
      }
    },

    getPersonByType(val,row){
      console.log(val);
      get_person_by_type(val).then(response => {

      });
    },
    updateforce(){
      console.log(111);
      this.$forceUpdate();
    },
    isNumber (val) {
      var regPos = /^\d+(\.\d+)?$/
      var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/
      if (regPos.test(val) || regNeg.test(val)) {
        return true
      } else {
        return false
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        constructEnterprise: null,
        bidedTime: null,
        estimatedCompleteTime: null,
        completedTime: null,
        bidAmount: null,
        estimatedBidTime: null,
        wallArea: null,
        projectManager: null,
        keyPoints: null,
        personOptions:null
      };
      this.currentProjectPresonMapList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeBidedTime = [];
      this.daterangeEstimatedCompleteTime = [];
      this.daterangeCompletedTime = [];
      this.daterangeEstimatedBidTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目基本资料";
      select_pms().then(response => {
        this.options = response.data.pms;
        this.personOptions = response.data.cascader;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids
      getCurrent_project(projectId).then(response => {
        this.form = response.data;
        this.currentProjectPresonMapList = response.data.currentProjectPresonMapList;
        this.personOptions = response.data.typePersonList;
        this.open = true;
        this.title = "修改项目基本资料";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.currentProjectPresonMapList = this.currentProjectPresonMapList;
          if (this.form.projectId != null) {
            updateCurrent_project(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCurrent_project(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      var deleteTitle = row.projectName? ('"'+row.projectName+'"'):'';
      this.$modal.confirm('是否确认删除' + deleteTitle + '？').then(function() {
        return delCurrent_project(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 现存项目与人员关联序号 */
    rowCurrentProjectPresonMapIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 现存项目与人员关联添加按钮操作 */
    handleAddCurrentProjectPresonMap() {
      let obj = {};
      obj.tempPersonName = "";
      this.currentProjectPresonMapList.push(obj);
    },
    /** 现存项目与人员关联删除按钮操作 */
    handleDeleteCurrentProjectPresonMap() {
      if (this.checkedCurrentProjectPresonMap.length == 0) {
        this.$modal.msgError("请先选择要删除的现存项目与人员关联数据");
      } else {
        const currentProjectPresonMapList = this.currentProjectPresonMapList;
        const checkedCurrentProjectPresonMap = this.checkedCurrentProjectPresonMap;
        this.currentProjectPresonMapList = currentProjectPresonMapList.filter(function(item) {
          return checkedCurrentProjectPresonMap.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleCurrentProjectPresonMapSelectionChange(selection) {
      this.checkedCurrentProjectPresonMap = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/current_project/export', {
        ...this.queryParams
      }, `current_project_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
